﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Super.Common;
using Super.Entities;
using Super.Infrastructure;

namespace Super.DomainService
{
    public class SettingService
    {
        private readonly DbContextAdapter _adp;
        private readonly BaseService<KeyValue> _keyvalueService;
        private static SettingInfo _settingInfo;
        static readonly object Lockhelper = new object();
      

        public SettingService(DbContextAdapter adapter)
        {
            _adp = adapter;
            _keyvalueService = new BaseService<KeyValue>(_adp);
        }

        public SettingInfo GetSetting()
        {

            //return DataCache.Get("bkSetting", () =>
            //{
            //    var settingModel = _keyvalueService.Repository.Find(a => a.Key == "WebSetting").FirstOrDefault();
            //    object obj = DeSerialize(typeof(SettingInfo), settingModel.Value);
            //    return (SettingInfo)obj;
            //}

            //        , TimeSpan.FromMinutes(40)) as SettingInfo;


            if (_settingInfo == null)
            {
                lock (Lockhelper)
                {
                    if (_settingInfo == null)
                    {
                        var settingModel = _keyvalueService.Repository.Find(a => a.Key == "WebSetting").FirstOrDefault();
                        if (settingModel == null)
                        {
                            return null;
                        }
                        var obj = Common.JsonHelper.JsonToObject<SettingInfo>(settingModel.Value);
                           
                        _settingInfo = obj;

                    }
                }

            }

            return _settingInfo;

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public bool UpdateSetting(SettingInfo settingInfo)
        {

            var settingModel = _keyvalueService.Repository.Find(a => a.Key == "WebSetting").FirstOrDefault();

            if (settingModel == null)
            {
                throw new Exception("没找到配置文件!");
            }

            settingModel.Value = Common.JsonHelper.ObjectToJson(settingInfo);

            lock (Lockhelper)
            {
                _settingInfo = settingInfo;
            }

            _keyvalueService.Repository.Update(settingModel);

            return _adp.ErrorMessage == null;

        }


    }
}
